import { defineConfig, loadEnv } from 'vite'
import { UserConfigExport, ConfigEnv } from 'vite' //mock
import { viteMockServe } from 'vite-plugin-mock'

import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons' // 引入svg插件
import path from 'path'

export default ({ command }: ConfigEnv, mode: string): UserConfigExport => {
    /**
     * loadEnv(mode, root) 读取环境变量
     * @param mode: 'development' | 'production' | 'test' 当前模式
     * @param root: string 项目环境变量根目录
     */
    const env = loadEnv(mode, process.cwd())

    return {
        plugins: [
            vue(),
            createSvgIconsPlugin({
                // Specify the icon folder to be cached
                iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
                symbolId: 'icon-[dir]-[name]',
            }),
            viteMockServe({
                localEnabled: command === 'serve', // 开发环境下开启mock
            }),
        ],
        resolve: {
            alias: {
                '@': path.resolve('./src'), // 相对路径别名配置，使用 @ 代替 src
            },
        },
        css: {
            preprocessorOptions: {
                scss: {
                    javascriptEnabled: true,
                    additionalData: '@import "./src/styles/variable.scss";', // 全局引入scss变量
                },
            },
        },
        server: {
            proxy: {
                [env.VITE_BASE_API]: {
                    target: env.VITE_SERVER_URL, // 代理接口地址
                    changeOrigin: true, // 开启代理
                    rewrite: (path) => path.replace(/^\/api/, ''), // 去掉代理地址中的api字符串
                },
            },
        },
    }
}
